package cn.jg.framework.common.util;

import cn.jg.framework.common.exception.BadRequestException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author fanfeveryahoo@gmail.com
 * @date 2019/12/12
 */
@Slf4j
public class EncodingUtils {

    private EncodingUtils() {
    }

    /**
     * Hex编码.
     */
    public static String encodeHex(byte[] input) {
        return Hex.encodeHexString(input);
    }

    /**
     * Hex解码.
     */
    public static byte[] decodeHex(String input) {
        try {
            return Hex.decodeHex(input.toCharArray());
        } catch (DecoderException e) {
            log.error("error", e);
        }
        return null;
    }

    /**
     * Html 转码.
     */
    public static String escapeHtml(String html) {
        return StringEscapeUtils.escapeHtml4(html);
    }

    /**
     * Html 解码.
     */
    public static String unescapeHtml(String htmlEscaped) {
        return StringEscapeUtils.unescapeHtml4(htmlEscaped);
    }

    public static String encodeUrlPath(String path) {
        try {
            String encodedUrl = URLEncoder.encode(path, StandardCharsets.UTF_8.name());
            return StringUtils.replace(encodedUrl, "\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new BadRequestException("url path encoding error: " + path, e);
        }
    }

    public static String encodeUrlFilename(String url) {
        String filename = StringUtils.substringAfterLast(url, "/");

        if (StringUtils.isBlank(filename)) {
            return url;
        }

        return StringUtils.substringBeforeLast(url, "/") + "/" + encodeUrlPath(filename);
    }
}
